package cn.shopifymall.externalTaskJava.component;

import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.client.ExternalTaskClient;
import org.camunda.bpm.engine.variable.Variables;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @Author 孤风雪影
 * @Email gitee.com/efairy520
 * @Date 2022/12/27 21:38
 * @Version 1.0
 */
@Component
@Slf4j
public class SubscribeTask {
    //流程引擎url
    private final String CAMUNDA_BASE_URL = "http://localhost:8717/engine-rest";

    /**
     * 消费者，消费流程引擎生成的task
     */
    private ExternalTaskClient client = null;

    private ExternalTaskClient getClient() {
        if (client == null) {
            client = ExternalTaskClient.create()
                    .baseUrl(CAMUNDA_BASE_URL)
                    .asyncResponseTimeout(10000)
                    .build();
        }
        return client;
    }

    /**
     * Step1：加入购物车
     */
    @PostConstruct
    public void handleShoppingCart() {
        getClient().subscribe("shopping_cart")
                .processDefinitionKey("shopping")
                .lockDuration(2000)
                .handler((externalTask, externalTaskService) -> {
                    log.info("订阅到加入购物车任务");
                    Map<String, Object> goodVariable = Variables.createVariables()
                            .putValue("size", "xl")
                            .putValue("count", 2);
                    externalTaskService.complete(externalTask, goodVariable);
                })
                .open();
    }

    /**
     * Step3：物流发货
     */
    @PostConstruct
    public void handleLogisticsDelivery() {
        getClient().subscribe("logistics_delivery")
                .processDefinitionKey("shopping")
                .lockDuration(2000)
                .handler((externalTask, externalTaskService) -> {
                    String toWhere = externalTask.getVariable("toWhere");
                    log.info("收到发货任务，目的地{}", toWhere);
                    externalTaskService.complete(externalTask);
                })
                .open();
    }

}
